package com.hanrui.android.fragment.message.audit.proposal;


import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.model.IPickerViewData;
import com.blankj.utilcode.util.ToastUtils;
import com.hanrui.android.R;
import com.hanrui.android.activity.TermActivity;
import com.hanrui.android.activity.download.MyDownLoadActivity;
import com.hanrui.android.activity.message.audit.VoteDetailActivity;
import com.hanrui.android.library.base.BaseFragment;
import com.hanrui.android.constant.Constant;
import com.hanrui.android.model.BossListBean;
import com.hanrui.android.model.GetNextActvityBean;
import com.hanrui.android.model.ProposalVoteDetailBean;
import com.hanrui.android.net.contract.message.audit.proposal.ProposalVoteBizContract;
import com.hanrui.android.net.presenter.message.audit.proposal.ProposalVoteBizPresenter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 董事会表决审批流程
 */

public class ProposalVoteBizFragment extends BaseFragment<ProposalVoteBizPresenter> implements ProposalVoteBizContract.View {

    @BindView(R.id.next)
    LinearLayout nextLl;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.name_go)
    ImageView nameGo;
    @BindView(R.id.bm_ll)
    LinearLayout bmLl;
    @BindView(R.id.bm)
    TextView bm;
    @BindView(R.id.bm_go)
    ImageView bmGo;
    @BindView(R.id.reson_ll)
    LinearLayout resonLl;
    @BindView(R.id.reson)
    EditText reson;
    @BindView(R.id.extra_ll)
    LinearLayout extraLl;
    @BindView(R.id.boss_ll)
    LinearLayout bossLl;
    @BindView(R.id.boss_name)
    TextView bossName;
    @BindView(R.id.boss_go)
    ImageView bossGo;
    @BindView(R.id.fact_ll)
    LinearLayout factLl;
    @BindView(R.id.fact_boss)
    EditText factBoss;
    @BindView(R.id.ll_addview)
    LinearLayout lladdview;


    String taskId,procInsId,bizId;
    String transitionId = "";
    String nextAssigneeList = "";
    String meetingUser = "";
    //String actualAttendees = "";
    String proposalList = "";

    OptionsPickerView pvOptions,userOptions;

    ArrayList<GetNextActvityBean.NextActivityBean.NextAssigneeListBean> dataList = new ArrayList<>();
    List<ProposalVoteDetailBean.ResultBean> resultBeanList;

    GetNextActvityBean.NextActivityBean bean;

    JSONArray jsonArray;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_proposalvotebiz;
    }

    @Override
    protected void initInjector() { mFragmentComponent.inject(this); }

    @Override
    protected void initView(View view) {

        taskId = getArguments().getString("taskId");
        procInsId = getArguments().getString("procInsId");
        bizId = getArguments().getString("bizId");

        mPresenter.getNextActivity(getActivity(),taskId,procInsId,bizId);

    }

    //实例化
    public static ProposalVoteBizFragment newInstance(String taskId, String procInsId, String bizId) {
        ProposalVoteBizFragment fragment = new ProposalVoteBizFragment();
        Bundle bundle = new Bundle();
        bundle.putString("taskId", taskId);
        bundle.putString("procInsId", procInsId);
        bundle.putString("bizId", bizId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void getNextActivity(GetNextActvityBean data) {

        name.setText(data.getNextActivity().getName());
        bean = data.getNextActivity();

        if (bean.getType().equals("endEvent")) {

            bmLl.setVisibility(View.GONE);
            resonLl.setVisibility(View.GONE);
            reson.setText("");
            factLl.setVisibility(View.VISIBLE);
            mPresenter.proposalVoteBizDetail(getActivity(),taskId,procInsId,bizId);
            return;

        		}

        if (null != bean.getTransitions() && bean.getTransitions().size() > 0) {

            List<GetNextActvityBean.NextActivityBean.TransitionsListBean> transitionsList = bean.getTransitions();

            name.setText(transitionsList.get(0).getName());
            transitionId = transitionsList.get(0).getId();

            if (null != transitionsList.get(0).getNextAssigneeList() && transitionsList.get(0).getNextAssigneeList().size() >0) {

                bm.setText(transitionsList.get(0).getNextAssigneeList().get(0).getName());
                nextAssigneeList = transitionsList.get(0).getNextAssigneeList().get(0).getId();

                getTransitionNextActivity(transitionsList.get(0).getNextAssigneeList());

            }else {

                bmLl.setVisibility(View.GONE);
                nextAssigneeList = "";

            }

            if (transitionsList.size() == 1) {

                name.setText(bean.getName());
                nextLl.setEnabled(false);
                nameGo.setVisibility(View.GONE);


            		}else {

                nextLl.setEnabled(true);
                nameGo.setVisibility(View.VISIBLE);

                pvOptions = new OptionsPickerView.Builder(getActivity(), new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        transitionId = bean.getTransitions().get(options1).getId();
                        name.setText(bean.getTransitions().get(options1).getPickerViewText());
                        if (null != bean.getTransitions().get(options1).getNextAssigneeList() &&
                                bean.getTransitions().get(options1).getNextAssigneeList().size() > 0) {

                            bmLl.setVisibility(View.VISIBLE);
                            bm.setText(bean.getTransitions().get(options1).getNextAssigneeList().get(0).getName());
                            nextAssigneeList = bean.getTransitions().get(options1).getNextAssigneeList().get(0).getId();
                            getTransitionNextActivity(bean.getTransitions().get(options1).getNextAssigneeList());

                        }else {

                            bmLl.setVisibility(View.GONE);
                            bm.setText("");
                            bm.setHint("请选择");
                            nextAssigneeList = "";
                        }

                    }
                }).build();
                pvOptions.setPicker(bean.getTransitions());

            }

        		}else {


            if (null != bean.getNextAssigneeList() && bean.getNextAssigneeList().size() > 0) {

                nextAssigneeList = bean.getNextAssigneeList().get(0).getId();
                bm.setText(bean.getNextAssigneeList().get(0).getName());
                getTransitionNextActivity(bean.getNextAssigneeList());

            }else {

                bmLl.setVisibility(View.GONE);
                nextAssigneeList = "";

            }

        }

        if (bean.getName().equals("董事会专员备案")) {

            mPresenter.getDirectorLeaderList(getActivity());


        		}


    }


    private void getTransitionNextActivity(List<GetNextActvityBean.NextActivityBean.NextAssigneeListBean> nextAssigneeList) {

        if (nextAssigneeList.size() == 1) {

            bmLl.setEnabled(false);
            bmGo.setVisibility(View.GONE);

        }else {

            bmLl.setEnabled(true);
            bmGo.setVisibility(View.VISIBLE);
            dataList.clear();
            dataList.addAll(nextAssigneeList);
            bmLl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    TermActivity.start(ProposalVoteBizFragment.this, Constant.nextactivity,dataList,false);
                }
            });

        }

    }

    @Override
    public void proposalVoteBizApproval(int code) {
        if (code == 1) {

            ToastUtils.showShort("提交成功");
            getActivity().finish();

        		}else {

            ToastUtils.showShort("提交失败");
        }

    }

    @Override
    public void getDirectorLeaderList(final List<BossListBean.ListDateBean> dataList) {

        if (null != dataList && dataList.size() > 0) {

            extraLl.setVisibility(View.VISIBLE);
            bossName.setText(dataList.get(0).getName());
            meetingUser = dataList.get(0).getId();
            bossLl.setEnabled(false);
            bossGo.setVisibility(View.GONE);

            if (dataList.size() > 1) {

                bossGo.setVisibility(View.VISIBLE);
                bossLl.setEnabled(true);
                bossLl.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        TermActivity.start(ProposalVoteBizFragment.this, Constant.leader,dataList,false);

                    }
                });


            		}



        		}


    }

    @Override
    public void proposalVoteBizDetail(ProposalVoteDetailBean data) {

        if (null != data && null != data.getResult() && data.getResult().size() > 0) {

            resultBeanList = data.getResult();
            lladdview.setVisibility(View.VISIBLE);

            for (int i = 0; i < resultBeanList.size(); i++) {

                addViewItem(resultBeanList.get(i));

            }

        		}

    }

    //添加ViewItem
    private void addViewItem(final ProposalVoteDetailBean.ResultBean bean) {
        View hotelEvaluateView = View.inflate(getActivity(), R.layout.item_vote, null);
        TextView billName = hotelEvaluateView.findViewById(R.id.bill_name);
        TextView thingTitle = hotelEvaluateView.findViewById(R.id.thing_title);
        TextView time = hotelEvaluateView.findViewById(R.id.time);
        TextView agree = hotelEvaluateView.findViewById(R.id.agree);
        TextView oppose = hotelEvaluateView.findViewById(R.id.oppose);
        TextView waiver = hotelEvaluateView.findViewById(R.id.waiver);
        LinearLayout bmLl = hotelEvaluateView.findViewById(R.id.bm_ll);
        final TextView bm = hotelEvaluateView.findViewById(R.id.bm);
        ImageView enclosure = hotelEvaluateView.findViewById(R.id.enclosure);
        TextView voteDetail = hotelEvaluateView.findViewById(R.id.vote_detail);

        billName.setText(bean.getPROPOSAL());
        thingTitle.setText(bean.getOFFICENAME());
        time.setText(bean.getNAME());
        agree.setText(bean.getTONGYI()+"");
        oppose.setText(bean.getQIQUAN()+"");
        waiver.setText(bean.getFANDUI()+"");

        final List<AgreeBean> dataList = getDataList();

        userOptions = new OptionsPickerView.Builder(getActivity(), new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {

                bm.setText(dataList.get(options1).getPickerViewText());

            }
        }).build();
        userOptions.setPicker(getDataList());


        bmLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (userOptions != null) {

                    userOptions.show();
                		}
            }
        });


        enclosure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                MyDownLoadActivity.start(getActivity(),bean.getFileList());

            }
        });

        voteDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                VoteDetailActivity.start(getActivity(),bean.getPROPOSALID());

            }
        });

        lladdview.addView(hotelEvaluateView);
    }


    private void getProposalList(){

        if (jsonArray == null) {

            jsonArray = new JSONArray();
        }

        for (int i = 0; i < lladdview.getChildCount(); i++) {

            View childAt = lladdview.getChildAt(i);
            TextView vote = childAt.findViewById(R.id.bm);

            String str = vote.getText().toString();

            if (TextUtils.isEmpty(str)) {

                ToastUtils.showShort("请选择表决");
                return;

            		}
            String result;
            if (str.equals("通过")) {
                result = "0";
            		}else {
                result = "1";
            }

            JSONObject tmpObj = new JSONObject();

            try {
                tmpObj.put("id",resultBeanList.get(i).getPROPOSALID());
                tmpObj.put("result",result);
                jsonArray.put(tmpObj);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


        proposalList = jsonArray.toString();
        mPresenter.proposalVoteBizApproval(getActivity(),nextAssigneeList,taskId,procInsId,bizId,transitionId,reson.getText().toString(),meetingUser,factBoss.getText().toString(),proposalList);
        jsonArray = null;

    }


    @OnClick({R.id.next_ll,R.id.login_out})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.next_ll:
                if (null != pvOptions)
                    pvOptions.show();
                break;
            case R.id.login_out:
                if (bean.getType().equals("endEvent")) {

                    if (TextUtils.isEmpty(factBoss.getText().toString())) {

                        ToastUtils.showShort("请填写实际参会董事");
                        return;

                    		}

                    if (resultBeanList.size() > 0) {

                        getProposalList();
                        return;
                    }

                }
                mPresenter.proposalVoteBizApproval(getActivity(),nextAssigneeList,taskId,procInsId,bizId,transitionId,reson.getText().toString(),meetingUser,factBoss.getText().toString(),proposalList);
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case Constant.nextactivity:
                if (null != data) {
                    String result = data.getStringExtra("data");
                    String countING = data.getStringExtra("id");
                    if (null != result && !"".equals(result)) {
                        bm.setText(result);
                    }
                    nextAssigneeList = countING;
                }
                break;
                case Constant.leader:
                    if (null != data) {
                        String result = data.getStringExtra("data");
                        String countING = data.getStringExtra("id");
                        if (null != result && !"".equals(result)) {
                            bossName.setText(result);
                        }
                        meetingUser = countING;
                    }
                    break;
        }
    }


    private class JsonBean {
        String id;
        String result;

        public JsonBean(String id, String result) {
            this.id = id;
            this.result = result;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getResult() {
            return result;
        }

        public void setResult(String result) {
            this.result = result;
        }
    }



    private class AgreeBean implements IPickerViewData{
        String name;

        public AgreeBean(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String getPickerViewText() {
            return name;
        }
    }

    private List<AgreeBean> getDataList(){

        List<AgreeBean> datList = new ArrayList<>();


        datList.add(new AgreeBean("通过"));
        datList.add(new AgreeBean("不通过"));

        return  datList;

    }

}
